#include "NoiseSphere.h"
#include "Ray.h"
#include <math.h>
#include "HTCalc.h"
#include <ctime>


NoiseSphere::NoiseSphere(){
	noiseOffset.x = 0;
	noiseOffset.y = 0;
	noiseOffset.z = 0;
}

float NoiseSphere::Density(D3DXVECTOR3 &point)
{
	D3DXVECTOR3 temp = point;
	//modulate point by turbulance
	temp = point * (1+HTCalc::Turbulence(point + noiseOffset,2, 4));

	//put point into sphere density function
	float rsub12 = pow((radius - softness/2),2);
	float rsub02 = pow((radius + softness/2),2);
	float rsubx2 = pow((temp.x - center.x),2) + pow((temp.y - center.y),2) + pow((temp.z - center.z),2);
	
	if(rsubx2 <= rsub12)
	{
		return 1.0f;
	}
	else if(rsubx2 >= rsub02)
	{
		return 0.0f;
	}
	else
	{
		return (rsub02 - rsubx2)/(rsub02 - rsub12);
	}	
}
void NoiseSphere::Normal(D3DXVECTOR3* normal, D3DXVECTOR3 &samplepoint, float epsilon, float sampledensity)
{
	//Given 'samplepoint' with a density of 'sampledensity'
	D3DXVECTOR3 temp = samplepoint;
	temp.x -= epsilon;

	D3DXVECTOR3* returnVec = new D3DXVECTOR3();
    returnVec->x = this->Density(temp) - sampledensity;

	temp = samplepoint;
	temp.y -= epsilon;
    returnVec->y = Density(temp) - sampledensity;

	temp = samplepoint;
	temp.z -= epsilon;
    returnVec->z = Density(temp) - sampledensity;

	::D3DXVec3Normalize(returnVec, returnVec);
	*normal = *returnVec;
}